const fs = require('fs');
const http= require('http');
const path = require('path');
const url = require('url');
const slugify = require('slugify');
// const textIn = fs.readFileSync('./txt/input.txt','utf-8'); // 不指定参数会得到arraybuffer
// const textOut= `this is what we know about the avocado:${textIn}.\nCreated on${Date.now()}`
// fs.writeFileSync('./txt/output.txt',textOut);
// console.log('文本写入完成')
// 替换html文本的占位符
const replaceTemplate = (temp,product)=>{
    let output = temp.replace(/{%PRODUCTNAME%}/g,product.productName);
    output = output.replace(/{%IMAGE%}/g,product.image);
    output = output.replace(/{%PRICE%}/g,product.price);
    output = output.replace(/{%FROM%}/g,product.from);
    output = output.replace(/{%NUTRIENTS%}/g,product.nutrients);
    output = output.replace(/{%QUANTITY%}/g,product.quantity);
    output = output.replace(/{%DESCRIPTION%}/g,product.description);
    output = output.replace(/{%ID%}/g,product.id);

    if(!product.organic){
        output = output.replace(/{%NOT_ORGANIC%}/g,'not-organic');
    }
    return output;
}

const dataJson = fs.readFileSync(`${__dirname}/dev-data/data.json`,'utf-8')
const dataObj = JSON.parse(dataJson)

// html文件
const tempOverview = fs.readFileSync(`${__dirname}/templates/template-overview.html`,'utf-8');
const tempCard = fs.readFileSync(`${__dirname}/templates/template-card.html`,'utf-8');
const tempProduct = fs.readFileSync(`${__dirname}/templates/template-product.html`,'utf-8');


const server = http.createServer((req, res)=>{
    
    const {query,pathname} = url.parse(req.url,true); //传入true解析为对象
    const pathName = pathname;
    if(pathName === '/' || pathName == '/overview'){
        const cardsHtml = dataObj.map(el => replaceTemplate(tempCard,el))
        const output = tempOverview.replace('{%PRODUCT_CARDS%}',cardsHtml);
        res.writeHead(200,{
            'Content-type':'text/html'
        });
        res.end(output)
        //res.end('this is the OverView'); // 中文编码会乱码
    }else if(pathName === '/product'){
        res.writeHead(200,{
            'Content-type':'text/html'
        });
        const product = dataObj[query.id];
        const output = replaceTemplate(tempProduct,product);
        console.log(product,output);
        res.end(output)
    }else if(pathName === '/api'){
        console.log(__dirname,'当前目录')
        res.writeHead(200,{
            'Content-type':'application/json',
        })
        res.writeHead(200,{'Content-type':'application/json'});
        res.end(data);
    }else{
        res.writeHead(404,{
            'Content-type':'text/html',
            'my-own-header':"hellow header",
        });
        res.end('<h1>Page not found!</h1>');
    }
    
})
server.listen(8000,'127.0.0.1',()=>{
    console.log('Listening to requests on port 8000');
})